package com.glory.dgcpcpda.activity.check;

import android.content.Intent;
import android.os.Build;
import android.os.Bundle;
import android.os.Parcelable;
import android.text.Editable;
import android.text.TextWatcher;
import android.view.View;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import androidx.annotation.RequiresApi;
import androidx.recyclerview.widget.RecyclerView;

import com.chad.library.adapter.base.BaseQuickAdapter;
import com.glory.dgcpcpda.R;
import com.glory.dgcpcpda.activity.check.QC_TaskExecuteNextActivity;
import com.glory.dgcpcpda.adapter.DataLinesAdapter;
import com.glory.dgcpcpda.adapter.QCformSpcLineItemAdapter;
import com.glory.dgcpcpda.base.BaseActivity;
import com.glory.dgcpcpda.base.MyApp;
import com.glory.dgcpcpda.entity.QCformEntity;
import com.glory.dgcpcpda.entity.response.BaseResponseBean;
import com.glory.dgcpcpda.utils.FreeApi_PopUtils;
import com.glory.dgcpcpda.utils.FreeUI_GeneralPop;
import com.glory.dgcpcpda.utils.NetUtils;
import com.google.gson.Gson;
import com.google.gson.JsonObject;
import com.google.gson.JsonParser;
import com.google.gson.reflect.TypeToken;
import com.lzy.okgo.model.Response;
import com.pda.platform.ui.ui_pdaplatform.callback.FreeUI_DialogEntityCallBack;
import com.pda.platform.ui.ui_pdaplatform.callback.FreeUI_EntityCallBack;
import com.pda.platform.ui.ui_pdaplatform.dialog.FreeUI_GeneralFragmentDialog;
import com.pda.platform.ui.ui_pdaplatform.utils_public.FreeApi_DialogUtils;
import com.pda.platform.ui.ui_pdaplatform.view.FreeUI_ClearEditText;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.OnClick;

public class QC_DataAcquisitionActivity extends BaseActivity {


    @BindView(R.id.tvTitle)
    TextView tvTitle;
    @BindView(R.id.tvBaseSubmit)
    TextView tvBaseSubmit;
    @BindView(R.id.llMain)
    LinearLayout llMain;
    @BindView(R.id.rvQCformSpcLineItem)
    RecyclerView rvQCformSpcLineItem;
    @BindView(R.id.tvEdcItemName)
    TextView tvEdcItemName;
    @BindView(R.id.tvEdcItemDesc)
    TextView tvEdcItemDesc;
    @BindView(R.id.tvSl)
    TextView tvSl;
    @BindView(R.id.flEdcName)
    FrameLayout flEdcName;
    @BindView(R.id.etEdcName)
    FreeUI_ClearEditText etEdcName;
    @BindView(R.id.ivEdcName)
    ImageView ivEdcName;

    private QCformSpcLineItemAdapter mQCformSpcLineItemAdapter;
    private QCformEntity.QCFORMINFO.SPCLINESINFO spclinesinfo;
    private QCformEntity qCformEntity;
    private FreeUI_GeneralPop mEdcNameListPop;
    private ArrayList<String> sList = new ArrayList<>();
    private String LocationId = "";


    @Override
    protected int getLayoutResId() {
        return R.layout.activity_data_acquisition;
    }

    @Override
    protected void initView() {
        tvTitle.setText("采集数据");
        setMainLayout(llMain);

    }

    @Override
    protected void initData() {
        Bundle bundle = getIntent().getExtras();
        spclinesinfo = (QCformEntity.QCFORMINFO.SPCLINESINFO) bundle.getSerializable("DATA");
        qCformEntity = (QCformEntity) bundle.getSerializable("EDCNAMELIST");
        LocationId = bundle.getString("LocationId");

        tvEdcItemName.setText(spclinesinfo.getEDCITEMNAME());
        tvEdcItemDesc.setText(spclinesinfo.getEDCITEMDESC());
        tvSl.setText(spclinesinfo.getUSL()+"/"+spclinesinfo.getSL()+"/"+spclinesinfo.getLSL());

        initRecyclerView(rvQCformSpcLineItem, this);
        mQCformSpcLineItemAdapter = new QCformSpcLineItemAdapter(spclinesinfo.getSPCLINEITEMS());
        mQCformSpcLineItemAdapter.openLoadAnimation(BaseQuickAdapter.ALPHAIN);
        mQCformSpcLineItemAdapter.isFirstOnly(true);
        rvQCformSpcLineItem.setAdapter(mQCformSpcLineItemAdapter);

        etEdcName.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @RequiresApi(api = Build.VERSION_CODES.N)
            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {
                if (qCformEntity.getEDCNAMELIST().size() == 0){
                    return;
                }
                sList.clear();
                qCformEntity.getEDCNAMELIST().forEach(name ->{
                    if (name.contains(s.toString())){
                        sList.add(name);
                    }
                });
                if (sList.size() == 0){
                    return;
                }
                mEdcNameListPop = FreeApi_PopUtils.getNormalPop(getApplicationContext(), flEdcName.getWidth(), sList.size() == 0?qCformEntity.getEDCNAMELIST():sList, ivEdcName, (codeS, i) -> {
                    etEdcName.setText(codeS);
                });
            }

            @Override
            public void afterTextChanged(Editable s) {

            }
        });
        if (spclinesinfo.getCOLLECTWAY().equals("自动")){
            getwbSpc();
        }
    }

    private void getwbSpc() {
        FreeUI_EntityCallBack<BaseResponseBean<QCformEntity>> callBack = new FreeUI_DialogEntityCallBack<BaseResponseBean<QCformEntity>>
                (new TypeToken<BaseResponseBean<QCformEntity>>() {
                }.getType(), getSupportFragmentManager(), this) {

            @RequiresApi(api = Build.VERSION_CODES.N)
            @Override
            public void onSuccess(Response<BaseResponseBean<QCformEntity>> response) {
                super.onSuccess(response);
                if (response.body().getResponse().getReturn().getReturnCode().equals("OK")) {
                    for (int i = 0; i < mQCformSpcLineItemAdapter.getData().size(); i++) {
                        mQCformSpcLineItemAdapter.getData().get(i).setDCDATA(response.body().getResponse().getBody().getDataList().get(i));
                    }
                    mQCformSpcLineItemAdapter.notifyDataSetChanged();
                }else {
                    FreeUI_GeneralFragmentDialog tipDialog = FreeApi_DialogUtils.getConfirmDialog(MyApp.app, "确定", response.body().getResponse().getReturn().getReturnMessage(), () -> {

                    });
                    tipDialog.show(getSupportFragmentManager(),"DIALOG");
                }
            }

            @Override
            public void onError(Response<BaseResponseBean<QCformEntity>> response) {
                super.onError(response);
                loadError(response.getException(),"TestMethod");
            }
        };

        JsonObject map = new JsonObject();
        map.addProperty("MeasuraEqpId",qCformEntity.getQCFORM().getEQUIPMENTID());
        if (qCformEntity.getLOCATIONLIST().size() > 0){
            map.addProperty("LocationId",qCformEntity.getLOCATIONLIST().get(0));
        }
        map.addProperty("TestMethod","Ball_Shear");
        map.addProperty("LotId",qCformEntity.getQCFORM().getLOTID());
        NetUtils.requestPostNet("TestMethod", "GetwbSpc", this, map, callBack);
    }

    @OnClick({R.id.tvBaseSubmit,R.id.flEdcName})
    public void onViewClicked(View view) {
        switch (view.getId()){
            case R.id.tvBaseSubmit:
                Intent intent = new Intent(QC_DataAcquisitionActivity.this, QC_TaskExecuteNextActivity.class);
                Bundle bundle= new Bundle();
                spclinesinfo.getQCFORMSPCLINEITEM().clear();
                List<QCformEntity.QCFORMINFO.SPCLINESINFO.QCFORMSPCLINE> data = mQCformSpcLineItemAdapter.getData();
                ArrayList<QCformEntity.QCFORMINFO.SPCLINESINFO.QCFORMSPCLINE> qcformspclines = new ArrayList<>();
                qcformspclines.addAll(data);
                spclinesinfo.setSPCLINEITEMS(qcformspclines);
                bundle.putSerializable("ITEMDATA", spclinesinfo);
                intent.putExtras(bundle);
                setResult(1, intent);
               // finish();
               // FreeApi_DialogUtils.getConfirmAndCancelDialog(this, result.equals("") ? "请确认是否提交?" : "有首检项目未录入数据，是否确认提交?", () -> {
                    FreeUI_EntityCallBack<BaseResponseBean<QCformEntity>> callBack = new FreeUI_DialogEntityCallBack<BaseResponseBean<QCformEntity>>
                            (new TypeToken<BaseResponseBean<QCformEntity>>() {
                            }.getType(), getSupportFragmentManager(), this) {

                        @Override
                        public void onSuccess(Response<BaseResponseBean<QCformEntity>> response) {
                            super.onSuccess(response);
                            if (response.body().isSuccess(getApplicationContext(), false, getSupportFragmentManager())) {
                                QC_TaskExecuteActivity.setMessage("1");
                                if (response.body().getResponse().getBody().getRESULTFLAG().equals("NG")) {
                                    FreeUI_GeneralFragmentDialog tipDialog = FreeApi_DialogUtils.getConfirmDialog(MyApp.app, "确定", "首检结果不通过，系统自动创建需要执行的首检单据为：" + response.body().getResponse().getBody().getQCFORMID(), () -> {
                                        //finish();
                                    });
                                    tipDialog.show(getSupportFragmentManager(), "DIALOG");
                                } else {
                                    showToast("提交成功", true);
                                        finish();

                                }
                            }
                        }

                        @Override
                        public void onError(Response<BaseResponseBean<QCformEntity>> response) {
                            super.onError(response);
                            loadError(response.getException(), "QCFORMCOMPLETE");
                        }
                    };
                    JsonObject map = new JsonObject();
                    QCformEntity.QCFORMINFO qcFormdata = new QCformEntity.QCFORMINFO();
                   /* data.setOBJECTRRN(qCformEntity.getQCFORM().getOBJECTRRN());
                    data.setQCFORMID(qCformEntity.getQCFORM().getQCFORMID());
                    data.setLOTID(qCformEntity.getQCFORM().getLOTID());
                    data.setINSPECTSTEPNAME(qCformEntity.getQCFORM().getINSPECTSTEPNAME());
                    data.setINSPECTTIMING(qCformEntity.getQCFORM().getINSPECTTIMING());
                    data.setINSPECTTYPE(qCformEntity.getQCFORM().getINSPECTTYPE());
                    data.setEQUIPMENTID(qCformEntity.getQCFORM().getEQUIPMENTID());
                    data.setLOCATIONID(qCformEntity.getQCFORM().getLOCATIONID());
                    data.setSTATE(qCformEntity.getQCFORM().getSTATE());
                    data.setNAME(qCformEntity.getQCFORM().getNAME());
                    data.setDESCRIPTION(qCformEntity.getQCFORM().getDESCRIPTION());
                    data.setSTEPNAME(qCformEntity.getQCFORM().getSTEPNAME());
                    data.setSTEPDESC(qCformEntity.getQCFORM().getSTEPDESC());
                    data.setCIRCUITNAME(qCformEntity.getQCFORM().getCIRCUITNAME());
                    data.setCUSTOMERCODE(qCformEntity.getQCFORM().getCUSTOMERCODE());
                    data.setMAINMATTYPE(qCformEntity.getQCFORM().getMAINMATTYPE());
                    data.setCOMMENTS2(tvResult.getText().toString());
                    data.setCOMMENT(etComment.getText().toString());
                    data.setDATANUMS(qCformEntity.getQCFORM().getDATANUMS());*/
                    qcFormdata.setOBJECTRRN(qCformEntity.getQCFORM().getOBJECTRRN());
                    ArrayList<QCformEntity.QCFORMINFO.SPCLINESINFO> spclinesinfos = new ArrayList<>();
                    spclinesinfos.add(spclinesinfo);
                    qcFormdata.setSPCLINES(spclinesinfos);

                    map.add("QCFORM", new JsonParser().parse(new Gson().toJson(qcFormdata)).getAsJsonObject());
                    map.addProperty("ACTIONTYPE","saveSpc");
                    NetUtils.requestPostNet("CPC.QCFORMCOMPLETE", "TRANSFERMES", this, map, callBack);
                //}, () -> {
              //  }).show(getSupportFragmentManager(), "QCFORMCOMPLETE");
                break;
            case R.id.flEdcName:
                if (mEdcNameListPop != null) {
                    if (mEdcNameListPop.isShowing()) {
                        mEdcNameListPop.dismiss();
                    }
                } else {
                    mEdcNameListPop = FreeApi_PopUtils.getNormalPop(getApplicationContext(), flEdcName.getWidth(), qCformEntity.getEDCNAMELIST(), ivEdcName, (codeS, i) -> {
                        etEdcName.setText(codeS);
                    });
                }
                FreeApi_PopUtils.setArrowShow(ivEdcName);
                mEdcNameListPop.showAsDropDown(flEdcName, 0, 0);
                break;
        }

    }
}
